<template>
  <basic-container>
    <avue-crud :data="data" :option="option" :page.sync="page" :table-loading="loading" :key="componentKey"
      @on-load="getList" @search-change="searchChange" @search-reset="searchReset" @refresh-change="refreshChange"
      @row-update="rowUpdate" @row-del="rowDel" @current-change="currentChange" @size-change="sizeChange" ref="crud">
      <template slot="images" slot-scope="scope">
        <div v-if="scope.row.images && scope.row.images.length > 0">
          <el-image :src="scope.row.images_full ? scope.row.images_full[0] : scope.row.images[0]"
            :preview-src-list="scope.row.images_full || scope.row.images" fit="cover"
            style="width: 50px; height: 50px; border-radius: 4px;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-if="scope.row.images.length > 1" style="margin-left: 5px; color: #409EFF; font-size: 12px;">
            +{{ scope.row.images.length - 1 }}
          </span>
        </div>
        <span v-else style="color: #999;">无图片</span>
      </template>
      <template #menu="{ row, index, size }">
        <el-button type="text" @click="handleView(row, index)">查看</el-button>
        <el-button type="text" @click="handleReview(row, index)">回复</el-button>
      </template>
    </avue-crud>

    <!-- 查看详情弹窗 -->
    <el-dialog title="查看详情" :visible.sync="viewDialogVisible" width="800px" :close-on-click-modal="false"
      :modal-append-to-body="true" custom-class="view-dialog" :z-index="9999" :append-to-body="true">
      <div class="consultation-detail">
        <!-- 基本信息表格 -->
        <el-table :data="detailTableData" border stripe size="small" class="detail-table">
          <el-table-column prop="label" label="字段" width="120" align="center" class-name="label-column">
            <template slot-scope="scope">
              <span class="field-label">{{ scope.row.label }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="内容" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.type === 'content'" class="content-cell">
                {{ scope.row.value }}
              </div>
              <div v-else-if="scope.row.type === 'status'" class="status-cell">
                <span :class="getStatusClass(scope.row.value)">{{ scope.row.value }}</span>
              </div>
              <div v-else-if="scope.row.type === 'images'" class="images-cell">
                <div class="image-gallery">
                  <el-image v-for="(img, index) in scope.row.images" :key="index" :src="img"
                    :preview-src-list="scope.row.images" fit="cover" class="gallery-image">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
              <div v-else class="normal-cell">
                {{ scope.row.value || '暂无' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 回复弹窗 -->
    <el-dialog title="回复咨询" :visible.sync="replyDialogVisible" width="800px" :close-on-click-modal="false"
      :modal-append-to-body="true" custom-class="reply-dialog" :z-index="9999" :append-to-body="true">
      <div class="consultation-detail">
        <!-- 基本信息表格 -->
        <el-table :data="replyTableData" border stripe size="small" class="detail-table">
          <el-table-column prop="label" label="字段" width="120" align="center" class-name="label-column">
            <template slot-scope="scope">
              <span class="field-label">{{ scope.row.label }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="内容" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.type === 'content'" class="content-cell">
                {{ scope.row.value }}
              </div>
              <div v-else-if="scope.row.type === 'status'" class="status-cell">
                <span :class="getStatusClass(scope.row.value)">{{ scope.row.value }}</span>
              </div>
              <div v-else-if="scope.row.type === 'images'" class="images-cell">
                <div class="image-gallery">
                  <el-image v-for="(img, index) in scope.row.images" :key="index" :src="img"
                    :preview-src-list="scope.row.images" fit="cover" class="gallery-image">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
              <div v-else-if="scope.row.type === 'reply'" class="reply-cell">
                <el-input v-model="replyForm.reply_content" type="textarea" :rows="6" placeholder="请输入回复内容..."
                  maxlength="500" show-word-limit>
                </el-input>
              </div>
              <div v-else class="normal-cell">
                {{ scope.row.value || '暂无' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="replyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReply" :loading="replyLoading">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getConsultationList, updateReply, getFeedbackTypeList } from "./api";
import { mapGetters } from "vuex";
export default {
  data () {
    return {
      loading: false,
      data: [],
      query: {},
      componentKey: 0,
      feedbackTypeList: [], // 反馈类型列表
      editRules: {
        reply_content: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 1, max: 500, message: '回复内容长度在 1 到 500 个字符', trigger: 'blur' }
        ]
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: false,
        indexLabel: "序号",
        selection: false,
        menuWidth: 150,
        dialogWidth: 900,
        dialogHeight: 600,
        searchBtnText: "搜索",
        emptyBtnText: "重置",
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchBtnIcon: "el-icon-search",
        emptyBtnIcon: "el-icon-refresh",
        column: [
          {
            label: "咨询ID",
            prop: "id",
            width: 120
          },
          {
            label: "咨询内容",
            prop: "content",
            type: "textarea",
            span: 24,
            overHidden: true,
            viewDisplay: true,
            editDisplay: false
          },
          {
            label: "用户昵称",
            prop: "nickname",
            width: 120
          },
          {
            label: "联系电话",
            prop: "phone",
            width: 130
          },
          {
            label: "反馈类型",
            prop: "feedback_type_name",
            search: true,
            type: "select",
            dicData: [],
            width: 120
          },
          {
            label: "提交时间",
            prop: "created_at",
            startPlaceholder: '日期开始范围自定义',
            endPlaceholder: '日期结束范围自定义',
            searchSpan: 12,
            width: 160,
            searchPlaceholder: "请选择时间范围",
            searchClearable: true
          },
          {
            label: "图片",
            prop: "images",
            type: "upload",
            listType: "picture-card",
            span: 24,
            width: 100,
            formatter: (row) => {
              if (row.images && row.images.length > 0) {
                return row.images_full ? row.images_full[0] : row.images[0];
              }
              return '';
            },
            slot: true
          },
          {
            label: "回复时间",
            prop: "reply_at",
            type: "datetime",
            format: "YYYY-MM-DD HH:mm:ss",
            valueFormat: "YYYY-MM-DD HH:mm:ss",
            width: 160
          },
          {
            label: "回复内容",
            prop: "reply_content",
            type: "textarea",
            span: 24,
            overHidden: true,
            viewDisplay: true,
            editDisplay: true,
            rules: [
              {
                required: true,
                message: "请输入回复内容",
                trigger: "blur"
              }
            ]
          },

        ]
      },
      viewDialogVisible: false,
      detailTableData: [],
      replyDialogVisible: false,
      replyTableData: [],
      replyForm: {
        reply_content: ''
      },
      replyLoading: false,
      currentRow: null
    };
  },
  computed: {
    ...mapGetters(["permission"])
  },

  watch: {
    // 监听查询参数变化，确保时间选择器正确显示
    query: {
      handler (newVal) {
        if (newVal.created_at && Array.isArray(newVal.created_at)) {
          // 确保时间格式正确
          newVal.created_at = newVal.created_at.map(time => {
            if (time && typeof time === 'string') {
              return time.replace('T', ' ').substring(0, 19);
            }
            return time;
          });
        }
      },
      deep: true
    }
  },
  created () {
    // 获取反馈类型列表
    this.getFeedbackTypeList();
    // 初始化加载数据
    this.getList(this.page);
  },

  mounted () {
    // 强制刷新组件以确保时间选择器正确初始化
    this.$nextTick(() => {
      this.componentKey += 1;
    });
  },
  methods: {
    // 获取状态类型
    getStatusType (status) {
      const statusMap = {
        0: 'warning',
        1: 'primary',
        2: 'success'
      };
      return statusMap[status] || 'info';
    },

    // 获取状态文本
    getStatusText (status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成'
      };
      return statusMap[status] || '未知';
    },

    // 获取列表数据
    getList (page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
      };

      // 合并搜索参数
      const searchParams = {
        feedback_type: this.query.feedback_type_name || search.feedback_type_name
      };

      // 处理时间参数
      if (this.query.created_at || search.created_at) {
        const timeRange = this.query.created_at || search.created_at;
        if (Array.isArray(timeRange) && timeRange.length === 2) {
          // 确保时间格式正确
          searchParams.start_time = timeRange[0] ? timeRange[0].replace('T', ' ').substring(0, 19) : '';
          searchParams.end_time = timeRange[1] ? timeRange[1].replace('T', ' ').substring(0, 19) : '';
        } else if (typeof timeRange === 'string') {
          searchParams.start_time = timeRange.replace('T', ' ').substring(0, 19);
        }
      }

      console.log('原始查询参数:', this.query);
      console.log('搜索参数:', search);
      console.log('处理后的搜索参数:', searchParams);
      console.log('最终请求参数:', { ...param, ...searchParams });

      getConsultationList({ ...param, ...searchParams })
        .then((res) => {
          console.log('接口返回:', res);
          const resData = res.data;
          this.page.total = resData.total;
          this.data = resData.list;
          this.loading = false;
        })
        .catch((error) => {
          console.error('获取咨询列表失败:', error);
          this.$message.error('获取咨询列表失败');
          this.loading = false;
        });
    },

    // 搜索变化
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.getList(this.page, params);
      if (done) done();
    },

    // 搜索重置
    searchReset (done) {
      this.query = {};
      this.page.currentPage = 1;
      // 强制刷新组件以重置时间选择器
      this.componentKey += 1;
      this.$nextTick(() => {
        this.getList(this.page);
      });
      if (done) done();
    },

    // 刷新
    refreshChange () {
      this.getList(this.page, this.query);
    },

    // 当前页变化
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
      this.getList(this.page, this.query);
    },

    // 每页大小变化
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
      this.page.currentPage = 1;
      this.getList(this.page, this.query);
    },

    // 行更新
    rowUpdate (row, index, done, loading) {
      updateConsultationStatus({
        id: row.id,
        status: row.status
      })
        .then((res) => {
          if (res.err === 0) {
            this.$message.success('更新成功');
            this.getList(this.page, this.query);
          } else {
            this.$message.error(res.msg || '更新失败');
          }
          done();
        })
        .catch((error) => {
          console.error('更新失败:', error);
          this.$message.error('更新失败');
          done();
        });
    },

    // 行删除
    rowDel (row, done) {
      this.$confirm('确认删除该咨询记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteConsultation(row.id)
          .then((res) => {
            if (res.err === 0) {
              this.$message.success('删除成功');
              this.getList(this.page, this.query);
            } else {
              this.$message.error(res.msg || '删除失败');
            }
            if (done) done();
          })
          .catch((error) => {
            console.error('删除失败:', error);
            this.$message.error('删除失败');
            if (done) done();
          });
      }).catch(() => {
        if (done) done();
      });
    },

    // 查看详情
    handleView (row, index) {
      this.detailTableData = this.getDetailTableData(row);
      this.viewDialogVisible = true;
    },

    // 回复咨询
    handleReview (row, index) {
      this.currentRow = row; // 存储当前行数据
      this.replyTableData = this.getReplyTableData(row);
      this.replyForm.reply_content = ''; // 清空回复内容
      this.replyDialogVisible = true;
    },

    // 获取详情表格数据
    getDetailTableData (row) {
      const data = [
        {
          label: '咨询ID',
          value: row.id,
          type: 'normal'
        },
        {
          label: '用户昵称',
          value: row.nickname,
          type: 'normal'
        },
        {
          label: '联系电话',
          value: row.phone,
          type: 'normal'
        },
        {
          label: '反馈类型',
          value: row.feedback_type_name,
          type: 'normal'
        },
        {
          label: '创建时间',
          value: row.created_at,
          type: 'normal'
        },
        {
          label: '咨询内容',
          value: row.content,
          type: 'content'
        }
      ];

      // 如果有图片，添加图片字段
      if (row.images && row.images.length > 0) {
        data.push({
          label: '图片',
          value: '',
          type: 'images',
          images: row.images_full || row.images
        });
      }

      // 如果有回复，添加回复相关信息
      if (row.reply_at) {
        data.push({
          label: '回复时间',
          value: row.reply_at,
          type: 'normal'
        });
      }

      if (row.reply_content) {
        data.push({
          label: '回复内容',
          value: row.reply_content,
          type: 'content'
        });
      }

      return data;
    },

    // 获取回复表格数据
    getReplyTableData (row) {
      const data = [
        {
          label: '咨询ID',
          value: row.id,
          type: 'normal'
        },
        {
          label: '用户昵称',
          value: row.nickname,
          type: 'normal'
        },
        {
          label: '联系电话',
          value: row.phone,
          type: 'normal'
        },
        {
          label: '反馈类型',
          value: row.feedback_type_name,
          type: 'normal'
        },
        {
          label: '创建时间',
          value: row.created_at,
          type: 'normal'
        },
        {
          label: '咨询内容',
          value: row.content,
          type: 'content'
        }
      ];

      // 如果有图片，添加图片字段
      if (row.images && row.images.length > 0) {
        data.push({
          label: '图片',
          value: '',
          type: 'images',
          images: row.images_full || row.images
        });
      }

      // 添加回复内容字段
      data.push({
        label: '回复内容',
        value: '',
        type: 'reply'
      });

      return data;
    },

    // 提交回复
    submitReply () {
      if (!this.replyForm.reply_content.trim()) {
        this.$message.warning('请输入回复内容');
        return;
      }

      this.replyLoading = true;
      updateReply({
        id: this.currentRow.id,
        content: this.replyForm.reply_content
      })
        .then((res) => {
          if (res.err === 0) {
            this.$message.success('回复成功');
            this.replyDialogVisible = false;
            this.getList(this.page, this.query);
          } else {
            this.$message.error(res.msg || '回复失败');
          }
        })
        .catch((error) => {
          console.error('回复失败:', error);
          this.$message.error('回复失败');
        })
        .finally(() => {
          this.replyLoading = false;
        });
    },

    // 获取反馈类型列表
    getFeedbackTypeList () {
      getFeedbackTypeList()
        .then((res) => {
          if (res.err === 0 && res.data && res.data.list) {
            this.feedbackTypeList = res.data.list;
            // 更新表格配置中的反馈类型选项
            const feedbackTypeColumn = this.option.column.find(col => col.prop === 'feedback_type_name');
            if (feedbackTypeColumn) {
              feedbackTypeColumn.dicData = this.feedbackTypeList.map(item => ({
                label: item.name,
                value: item.id
              }));
            }
          }
        })
        .catch((error) => {
          console.error('获取反馈类型列表失败:', error);
        });
    },

    // 获取状态样式类
    getStatusClass (status) {
      if (status === '待处理') return 'status-pending';
      if (status === '处理中') return 'status-processing';
      if (status === '已完成') return 'status-completed';
      return 'status-normal';
    }
  }
};
</script>

<style scoped>
.consultation-list {
  padding: 20px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.el-image {
  cursor: pointer;
  transition: all 0.3s;
}

.el-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
.view-form,
.edit-form {
  padding: 20px;
}

.content-box {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px 16px;
  min-height: 60px;
  line-height: 1.6;
  word-break: break-all;
  white-space: pre-wrap;
}

.reply-content {
  background: #e8f4fd;
  border-color: #bee5eb;
  color: #0c5460;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.gallery-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  transition: all 0.3s;
}

.gallery-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
}

/* 回复按钮样式 */
.edit-form .el-textarea__inner {
  border-radius: 6px;
  border-color: #dcdfe6;
  transition: border-color 0.3s;
}

.edit-form .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 查看详情样式 */
.consultation-detail {
  .detail-table {
    .field-label {
      font-weight: bold;
      color: #333;
    }

    .content-cell {
      padding: 10px;
      background-color: #f8f9fa;
      border-radius: 4px;
      line-height: 1.6;
      white-space: pre-wrap;
      word-break: break-word;
      min-height: 60px;
    }

    .status-cell {
      .status-pending {
        color: #e6a23c;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #e6a23c;
          margin-right: 6px;
        }
      }

      .status-processing {
        color: #409eff;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #409eff;
          margin-right: 6px;
        }
      }

      .status-completed {
        color: #67c23a;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #67c23a;
          margin-right: 6px;
        }
      }

      .status-normal {
        color: #909399;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #909399;
          margin-right: 6px;
        }
      }
    }

    .images-cell {
      .image-gallery {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }

      .gallery-image {
        width: 60px;
        height: 60px;
        border-radius: 4px;
        border: 1px solid #e9ecef;
        transition: all 0.3s;
      }

      .gallery-image:hover {
        transform: scale(1.05);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .normal-cell {
      color: #606266;
    }

    .reply-cell {
      .el-textarea__inner {
        border-radius: 6px;
        border-color: #dcdfe6;
        transition: border-color 0.3s;
      }

      .el-textarea__inner:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
  }
}
</style>